<template>
  <myHeader :crumbs="crumbs"></myHeader>
  <div class="detail-main">
    <div class="board">
      <div class="top">
        <div class="Text">
          <p>答对<span class="result-right">{{ correctNum }}</span></p>
          <p>答错<span class="result-wrong">{{ errorNum }}</span></p>
        </div>
        <button @click="stateOpenFn">查看本次练题情况</button>
      </div>
      <div class="tips"><span class="active"></span>答对自动跳转下一题</div>
      <div class="list" ref="selectScrollRef">
        <ul>
          <li v-for="(item, index) in exercisesData" :key="index"
            :class="[index == exercisesIndex ? 'current' : '', item.answer ? item.correct ? 'right' : 'wrong' : '']" @click="pageSelectFn(index)">{{ index + 1 }}</li>
        </ul>
      </div>
    </div>
    <div class="content">
      <div class="anserTrue" style="color: red; font-size: 18px;"></div>
      <div class="title"><span>{{ infoData.type === 0 ? '单选题' : infoData.type === 1 ? '多选题' : '判断题' }}</span>
        <p>{{ infoData.question }}</p>
      </div>
      <img class="pic" :src="infoData.imgs[0]" alt="" v-if="infoData.imgs && infoData.imgs.length > 0">
      <div class="options">
        <template v-for="(item, index) in infoData.options" :key="index">
          <template v-if="infoData.type === 1">
            <div class="option" v-if="infoData.answer">
              <img src="@/assets/img/true.png" v-if="item.theme === 'success'">
              <img src="@/assets/img/error.png" v-else-if="item.theme === 'error'">
              <img src="@/assets/img/circle.png" v-else>{{ item.letter }}: <span v-html="item.title"></span>
            </div>
            <div class="option" :class="item.checked ? 'active' : ''" @click="selectFn(item)" v-else>
              <img src="@/assets/img/circle.png">{{ item.letter }}: <span v-html="item.title"></span>
            </div>
          </template>
          <template v-else>
            <div class="option" v-if="infoData.answer">
              <img src="@/assets/img/true.png" v-if="infoData.answer === item.letter && item.correct">
              <img src="@/assets/img/error.png" v-else-if="infoData.answer === item.letter && !item.correct">
              <img src="@/assets/img/circle.png" v-else>{{ item.letter }}: <span v-html="item.title"></span>
            </div>
            <div class="option" v-else @click="selectFn(item)">
              <img src="@/assets/img/circle.png">{{ item.letter }}: <span v-html="item.title"></span>
            </div>
          </template>
        </template>
      </div>
      <a href="javascript:;" class="button" :class="checkSubmitDisabled ? '' : 'button-active'"
        v-show="infoData.type === 1 && !infoData.answer" @click="checkSubmitFn">提交</a>
      <div class="page">
        <a href="javascript:;" class="prev" @click="pageChangeFn('prev')">上一题</a>
        <a href="javascript:;" class="next" @click="pageChangeFn('next')">下一题</a>
      </div>
      <template v-if="infoData.answer && infoData.answer !== infoData.correctAnswer">
        <div class="result">
          <span class="wrong">回答错误</span>
          <span class="right">正确答案：<i>{{ infoData.correctAnswer }}</i></span>
        </div>
        <!-- <div class="skill">
          <div class="til">本题技巧</div>
          <div class="cont">
            <p>秒懂技巧: {{ infoData.question.substring(0, 10) }}</p>
            <div class="bg"></div>
            <button @click="qrcodeVisible = true">查看完整技巧</button>
          </div>
        </div> -->
        <div class="explain" v-if="analysisChargedAuth">
          <div class="til">试题解析</div>
          <p>{{ infoData.analysis }}</p>
          <div class="diff">
            考友错误率：{{ (infoData.errorRate * 100).toFixed(2) }}%
          </div>
        </div>
        <div class="skill" v-else>
          <div class="til">试题解析</div>
          <div class="cont">
            <p>{{ infoData.analysis.substring(0, 24) + '...' }}</p>
            <div class="bg"></div>
            <button @click="analysisFn">查看完整解析</button>
          </div>
        </div>
      </template>
    </div>
    <el-image-viewer v-if="qrcodeVisible" :url-list="['/src/assets/img/qrcode.png']"
      @close="qrcodeVisible = false"></el-image-viewer>
    <el-dialog class="exercise-dialog" v-model="stateVisible" width="500" :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="false" align-center>
      <div class="box">
        <span class="close" @click="stateVisible = false; accuracy = 0"></span>
        <div class="top">
          <div class="canvas" width="180" height="180">
            <el-progress type="circle" :percentage="accuracy" :width="180" :stroke-width="10" :show-text="false"
              color="#FF9001" />
            <div class="canvas-statistic">
              <el-statistic value-style="font-size: 62px;line-height: 62px;font-weight: bold;" :value="accuracyOutput"
                :formatter="accuracyFn">
                <template #suffix>
                  <strong>%</strong>
                </template>
              </el-statistic>
              <div class="canvas-statistic-tips">正确率</div>
            </div>
          </div>
          <div class="Text">
            <div>
              <span>练题时长</span>
              <p>{{ exercisesTime }}</p>
            </div>
            <div>
              <span>练题数</span>
              <p>{{ answerSumNum }}</p>
            </div>
            <div>
              <span>本次错题</span>
              <p>{{ errorNum }}</p>
            </div>
          </div>
        </div>
        <div class="Text-desc">
          <p>根据你的错题情况，为你量身定制学习计划，提高考试通过率，扫码关注技考邦小程序获取吧！</p>
        </div>
        <div class="foot">
          <div>
            <p>小程序功能更多,体验更好!</p>
            <button>立即扫码关注技考邦小程序<img src="@/assets/img/exercise-dialog-right.png"></button>
          </div>
          <span class="foot-code" id="qrCode"></span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import myHeader from '@/components/header.component.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, getCurrentInstance, nextTick, onUnmounted } from 'vue';
const { $api } = getCurrentInstance().appContext.config.globalProperties;
import { useRoute, useRouter } from 'vue-router';
const route = useRoute()
const router = useRouter()
const exercisesData = ref([])
const exercisesIndex = ref(route.query.p || 0)
const exerciseId = ref(null)
const infoData = ref({})
const total = ref(0)
const lastParams = ref('all')
const selectScrollRef = ref()
const qrcodeVisible = ref(false)
const correctNum = ref(0)
const errorNum = ref(0)
const answerSumNum = ref(0)
const stateVisible = ref(false)
import { convertSecondsToHMS } from '@/utils/util.js';
const exercisesTime = ref('00:00')
const accuracy = ref(0.1)
import { useTransition } from '@vueuse/core';
const accuracyOutput = ref(0)
const checkSubmitDisabled = ref(true)
const answerArr = ref([])
const crumbs = ref([{
  name: '全部习题',
  url: ''
}])
const analysisChargedAuth = ref(false)

// 判断是否登录
if (!localStorage.getItem('token')) {
  router.replace('/login')
}
// 记录练习开始时间
if (!localStorage.getItem('exercisesStime')) {
  localStorage.setItem('exercisesStime', Date.now())
}
// 解析权限
if (localStorage.getItem('analysisChargedAuth')) {
  analysisChargedAuth.value = JSON.parse(localStorage.getItem('analysisChargedAuth'))
}
// 获取习题ids
const getListFn = () => {
  let selected = null;
  let chapter = null;
  let correct = null;
  // 精选
  if (route.name === 'type-subject-selected') {
    lastParams.value = 'selected';
    selected = true;
    crumbs.value = [{
      name: '精选练习',
      url: ''
    }]
  }
  // 章节
  if (route.name === 'type-subject-chapter-id') {
    lastParams.value = `chapter/${route.params.chapter}`;
    chapter = route.params.chapter;
    crumbs.value = [{
      name: '章节练习',
      url: `/${route.params.type}/${route.params.subject}/chapter`
    }, {
      name: route.query.cn || '',
      url: ''
    }]
  }
  // 错题本
  if (route.name === 'type-subject-wrong') {
    lastParams.value = 'wrong';
    correct = false;
    crumbs.value = [{
      name: '错题本',
      url: ''
    }]
  }
  $api.userExerciseRecordListApi({
    subjectId: route.params.subject,
    selected,
    chapter,
    correct
  }).then((res) => {
    if (res.errno === 0) {
      if (res.result && res.result.length > 0) {
        exercisesData.value = res.result;
        exerciseId.value = res.result[route.query.p || 0].exerciseId;
        total.value = res.result.length;
        getInfoFn()
        // 设置滚动条
        nextTick(() => {
          selectScrollRef.value.scrollTop = route.query.s ? Number(route.query.s) : 0;
        })
        // 答对 答错
        correctNum.value = res.result.filter(x => x.answer && x.correct).length;
        errorNum.value = res.result.filter(x => x.answer && !x.correct).length;
        answerSumNum.value = correctNum.value + errorNum.value;
      } else {
        ElMessageBox.confirm('当前科目下暂无习题数据', '系统提示', {
          showClose: false,
          showCancelButton: false,
          confirmButtonText: '我已知晓'
        }).then(() => {
          router.back()
        }).catch(() => {
          router.back()
        })
      }
      return false;
    }
    ElMessage.error(res.errmsg)
  })
}
getListFn()
// 习题详情
const getInfoFn = () => {
  $api.getExerciseApi({
    exerciseId: exerciseId.value
  }).then((res) => {
    if (res.errno === 0) {
      if (res.result) {
        // 多选题没有答题的数据追加checked、theme字段
        if (res.result.type === 1) {
          res.result.options.forEach(item => {
            item.checked = false;
            item.theme = '';
          })
          checkSubmitDisabled.value = true;
          // 回显多选项
          if (res.result.answer) {
            let _answer = res.result.answer.split('')
            if (res.result.answer === res.result.correctAnswer) {
              res.result.options.filter(x => _answer.includes(x.letter) ? x.theme = 'success' : x.theme = '')
            } else {
              res.result.options.filter(x => _answer.includes(x.letter) ? x.theme = 'error' : x.theme = '')
            }
          }
        }
        infoData.value = res.result;
      }
      return false;
    }
    ElMessage.error(res.errmsg)
  })
}
// 选题
const pageSelectFn = (val) => {
  exercisesIndex.value = val;
  router.replace(`/${route.params.type}/${route.params.subject}/${lastParams.value}?cn=${route.query.cn||''}&p=${val}&s=${selectScrollRef.value.scrollTop}`)
  exerciseId.value = exercisesData.value[val].exerciseId;
  getInfoFn()
}
// 上一题 下一题
const pageChangeFn = (val) => {
  if (val === 'prev' && exercisesIndex.value > 0) {
    exercisesIndex.value--;
    resetInfoFn()
  }
  if (val === 'next' && exercisesIndex.value + 1 < total.value) {
    exercisesIndex.value++;
    resetInfoFn()
  }
}
// 重定向习题详情
const resetInfoFn = () => {
  router.replace(`/${route.params.type}/${route.params.subject}/${lastParams.value}?cn=${route.query.cn||''}&p=${exercisesIndex.value}&s=${selectScrollRef.value.scrollTop}`)
  exerciseId.value = exercisesData.value[exercisesIndex.value].exerciseId;
  getInfoFn()
}
// 选择
const selectFn = (val) => {
  if (!infoData.value.answer) {
    // 单选 判断
    if (infoData.value.type === 0 || infoData.value.type === 2) {
      infoData.value.answer = val.letter;
      exercisesData.value[exercisesIndex.value].answer = val.letter;
      exercisesData.value[exercisesIndex.value].correct = val.letter === infoData.value.correctAnswer ? true : false;
      // 记录
      recordFn(infoData.value.id, val.letter)
      // 正确自动跳转下一题 答对数量自增
      if (val.letter === infoData.value.correctAnswer) {
        correctNum.value++;
        exercisesIndex.value++;
        resetInfoFn()
      }
      // 答错数量自增
      if (val.letter !== infoData.value.correctAnswer) {
        errorNum.value++;
      }
    }
    // 多选
    else {
      val.checked = !val.checked;
      checkSubmitDisabled.value = infoData.value.options.filter(x => x.checked).length > 1 ? false : true;
      infoData.value.options.forEach((item, index) => {
        answerArr.value[index] = item.checked ? item.letter : '';
      })
    }
    // 计算已答题数量
    answerSumNum.value = correctNum.value + errorNum.value;
  }
}
// 多选提交
const checkSubmitFn = () => {
  if (!checkSubmitDisabled.value) {
    let _answer = infoData.value.options.filter(x => x.checked).map(x => x.letter).join('')
    infoData.value.answer = _answer;
    exercisesData.value[exercisesIndex.value].answer = _answer;
    exercisesData.value[exercisesIndex.value].correct = _answer === infoData.value.correctAnswer ? true : false;
    // 记录
    recordFn(infoData.value.id, _answer)
    // 回显多选正确还是错误
    if (_answer === infoData.value.correctAnswer) {
      infoData.value.options.filter(x => x.checked ? x.theme = 'success' : x.theme = '')

      correctNum.value++;
      exercisesIndex.value++;
      resetInfoFn()
    } else {
      infoData.value.options.filter(x => x.checked ? x.theme = 'error' : x.theme = '')
      errorNum.value++;
    }
    // 计算已答题数量
    answerSumNum.value = correctNum.value + errorNum.value;
  }
}
// 习题记录
const recordFn = (exerciseId, answer) => {
  $api.addExerciseRecordApi({
    exerciseId,
    answer
  }).then((res) => {
    if (res.errno === 0) {
      return false;
    }
    ElMessage.error(res.errmsg)
  })
}
// 查看练题情况
const stateOpenFn = () => {
  if (localStorage.getItem('exercisesStime')) {
    let _remaining = Date.now() - Number(localStorage.getItem('exercisesStime'));
    exercisesTime.value = convertSecondsToHMS(_remaining / 1000)
    // 计算正确率 (答对数量 / 已答题数量) * 100%
    setTimeout(() => {
      accuracyOutput.value = useTransition(accuracy, {
        duration: 800
      })
      let _accuracy = parseInt((correctNum.value / answerSumNum.value) * 100);
      accuracy.value = (isNaN(_accuracy) || _accuracy <= 0) ? 0.1 : _accuracy;
    }, 90)
  }
  stateVisible.value = true;
}
// 自增长回显格式
const accuracyFn = (e) => {
  if (e.value) {
    return parseInt(e.value)
  }
}
// 查看完整解析
const analysisFn = () => {
  router.push(`/${route.params.type}/${route.params.subject}/pay`)
}
// 页面销毁
onUnmounted(() => {
  localStorage.removeItem('analysisChargedAuth')
  localStorage.removeItem('exercisesStime')
})
</script>

<style lang="scss" scoped>
@import '../assets/css/home.css';
@import '../assets/css/detail.css';

.detail-main .content .skill p {
  height: 32px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}

.exercise-dialog .foot .foot-code {
  width: 98px;
  height: 96px;
  margin-top: 1px;
}

.exercise-dialog .foot button {
  width: auto;
}

.canvas {
  float: left;
  margin: 61px 0 0 112px;
  position: relative;

  &-statistic {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    white-space: nowrap;

    &-tips {
      text-align: center;
      font-size: 14px;
      margin-top: 10px;
    }
  }
}
</style>
<style lang="scss">
.exercise-dialog {
  padding: 0;

  .el-dialog__header {
    display: none;
  }
}
</style>